One of the interview question is “How to find length of string in java without using length() method.”
There are many ways to find length of String. Some of them are :
Table of Contents [hide]
Using toCharArray is simplest solution.
Using toCharArray
Logic
- Convert string to char array using toCharArray method
- Iterate over char array and incrementing length variable.
Program
Using StringIndexOutOfBoundsException
You must be wondering how we can use
StringIndexOutOfBoundsException
to find length of String without using length() method. Please refer below logic :Logic
- Initialize
i
with0
and iterate over String without specifying any condition. So it will be always true. - Once value of
i
will be more than length of String, it will throwStringIndexOutOfBoundsException
exception. - We will
catch
the exception and return i after coming out ofcatch
block.
Program
Please go through java interview programs for more such programs and core java interview questions for more interview questions.
That’s all about How to find length of string in java without using length() method.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
HI Arpit
Your blog has been really good. We could achieve this also by recursion as follows.
public int length(String s) {
int l = 0;
/* Equate to empty string */
if (s.equals(“”)) {
return 0;
}
int index = 0;
l = length(s.substring(index+1)) + 1;
return l;
}
good logic